package com.asj.vivo.lock.service;

import static com.asj.enums.DeviceIdentifierDictEnums.json_key_deviceCode;
import static com.asj.enums.DeviceIdentifierDictEnums.json_key_isDeviceSendSync;
import static com.asj.enums.DeviceIdentifierDictEnums.syncDeviceInfo;

import android.annotation.SuppressLint;
import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Constraints;
import androidx.work.NetworkType;
import androidx.work.PeriodicWorkRequest;
import androidx.work.WorkManager;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.asj.service.command.specific.SpecificSyncDeviceInfoService;
import com.asj.service.oppoSdk.OPPOSDKService;
import com.asj.service.recover.RecoverDeviceInfoService;
import com.asj.utils.CommonsUtils;
import com.google.gson.JsonObject;

import java.util.Objects;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * 保证app存活，与后台通信的服务
 * */
public class StayAliveService extends Worker {
    @SuppressLint("StaticFieldLeak")
    public static Context context;

    private static UUID workId = null;

    public StayAliveService(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }


    /* 任务流程 */
    public static void taskFlow(Context param) throws Exception {
        if(param != null){
            context = param;
        }
        Log.w("定时任务","开始任务流程");
        if(context != null){
            JsonObject taskFlowData = new JsonObject();
            //获取当前设备的imei
            OPPOSDKService opposdkService = new OPPOSDKService(context);
            String deviceCode = CommonsUtils.getDeviceCode(opposdkService.getIMEI());
            taskFlowData.addProperty(json_key_deviceCode.getValue(),deviceCode);
            taskFlowData.addProperty(syncDeviceInfo.getValue(),"1");
            taskFlowData.addProperty(json_key_isDeviceSendSync.getValue(),true);

            /* 1.同步设备信息 */
            SpecificSyncDeviceInfoService.syncDeviceInfo(taskFlowData,context);
            Log.i("定时任务","同步设备信息 完成");
            /* 2.修正设备状态 */
            RecoverDeviceInfoService.correctDeviceStatusInfo(taskFlowData,null,context);
            Log.i("定时任务","修正设备状态 完成");
            /* 3.同步设备app信息，作为app安装监听器的后手，保证后台app数据与设备上的保持一致 */
            RecoverDeviceInfoService.correctDeviceAppInfo(context);
            Log.i("定时任务","同步设备app信息 完成");
            /* 4.同步后台设备监管限制项 */
            RecoverDeviceInfoService.correctDeviceRestrictInfo(context);
            Log.i("定时任务","同步后台设备监管限制项 完成");
        }
    }


    @NonNull
    @Override
    public Result doWork() {
        try {
            Log.w("创建","定时任务");
            taskFlow(context);
        } catch (Exception e) {
            Log.e("定时任务异常！", Objects.requireNonNull(e.getMessage()));
            return Result.failure();
        }
        return Result.success();
    }

    /**
     * 销毁所有定时任务
     * */
    public static void cancelAllWork(Context context){
        //启动任务前，将所有任务停止
        WorkManager workManager = WorkManager.getInstance(context);
        workManager.cancelAllWork();
        Log.w("销毁","全部定时任务");
    }

    /**
     * 设置和启动所有定时任务执行
     */
    public static void schedulePeriodicWork(Context context) {
        if(StayAliveService.context == null){
            StayAliveService.context =  context;
        }
        //如果存在定时任务则无需再次创建
        if(workId != null){
            return;
        }
        /*定义了任务执行所需的条件*/
        Constraints constraints = new Constraints.Builder()
                //setRequiredNetworkType(NetworkType.CONNECTED) 方法设置了任务必须在设备连接到互联网时执行的条件
                //NetworkType.CONNECTED 表示任务将在设备连接到任何类型的网络（例如 Wi-Fi 或移动数据）时执行
                .setRequiredNetworkType(NetworkType.CONNECTED)
                .setRequiresDeviceIdle(false)//空闲状态
                .setRequiresStorageNotLow(false)//存储空间
                .setRequiresStorageNotLow(false)//存储空间
                .build();
        /*定义了一个周期性的工作请求(一小时执行一次)*/
        PeriodicWorkRequest periodicWorkRequest =
                new PeriodicWorkRequest.Builder(StayAliveService.class, 1, TimeUnit.HOURS)
                .setConstraints(constraints)
                .build();
        //将定义好的一次性工作请求 syncRequest 添加到工作队列中。
        WorkManager workManager = WorkManager.getInstance(context);
        //enqueue() 方法会将工作请求安排到 WorkManager 的内部队列中，并在满足所有约束条件时执行它。
        workManager.enqueue(periodicWorkRequest);
        workId = periodicWorkRequest.getId();
    }
}
